//
//  WActionSheet.swift
//  iiatn
//
//  Created by mine on 18/4/19.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class WActionSheet: UIView, ShareDelegate{
    
    var mpro: WPro?
    
    class func show(pro: WPro){
        let actionSheet = WActionSheet()
        actionSheet.mpro = pro
        actionSheet.frame = UIScreen.main.bounds
        actionSheet.backgroundColor = WColor(r: 0, g: 0, b: 0, a: 0.6)
        let window = UIApplication.shared.keyWindow
        window?.addSubview(actionSheet)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        
        addSubview(bgView)
        
        // 上部 分享界面
        bgView.addSubview(topView)
        // 下部取消按钮
        bgView.addSubview(cancelButton)
        // 分享到 标签
        topView.addSubview(shareLabel)
        // 6 个分享按钮的 view
        topView.addSubview(shareButtonView)
        
        topView.snp.makeConstraints { (make) in
            make.bottom.equalTo(cancelButton.snp.top).offset(-kMargin)
            make.left.equalTo(cancelButton.snp.left)
            make.right.equalTo(cancelButton.snp.right)
            make.height.equalTo(kTopViewH)
        }
        
        cancelButton.snp.makeConstraints { (make) in
            make.left.equalTo(bgView).offset(kMargin)
            make.right.bottom.equalTo(bgView).offset(-kMargin)
            make.height.equalTo(44)
        }
        
        shareLabel.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(topView)
            make.height.equalTo(30)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        UIView.animate(withDuration: kAnimationDuration) {
            self.bgView.y = SCREENH - self.bgView.height
        }
    }
    
    // 底部 view
    private lazy var bgView: UIView = {
        let bgView = UIView()
        bgView.frame = CGRect(x: 0, y: SCREENH, width: SCREENW, height: 280)
        return bgView
    }()
    // 上部 view
    private lazy var topView: UIView = {
        let topView = UIView()
        topView.backgroundColor = UIColor.white
        topView.layer.cornerRadius = kCornerRadius
        topView.layer.masksToBounds = true
        return topView
    }()
    
    // 分享到标签
    private lazy var shareLabel: UILabel = {
        let shareLabel = UILabel()
        shareLabel.text = "\n------分享到------"
        shareLabel.textColor = WColor(r: 0, g: 0, b: 0, a: 0.7)
        shareLabel.textAlignment = .center
        return shareLabel
    }()
    // 6个按钮
    private lazy var shareButtonView: WShareButtonView = {
        let shareButtonView = WShareButtonView()
        shareButtonView.delegate = self
        shareButtonView.frame = CGRect(x: 0, y: 30, width: SCREENW - 20, height: kTopViewH - 30)
        return shareButtonView
    }()
    
    private lazy var cancelButton: UIButton = {
        let cancelButton = UIButton()
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        cancelButton.setTitleColor(WColor(r: 37, g: 142, b: 240, a: 1.0), for: .normal)
        cancelButton.backgroundColor = UIColor.white
        cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        cancelButton.layer.cornerRadius = kCornerRadius
        cancelButton.layer.masksToBounds = true
        return cancelButton
    }()
    
    func cancelButtonClick() {
        UIView.animate(withDuration: kAnimationDuration, animations: {
            self.bgView.y = SCREENH
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        UIView.animate(withDuration: kAnimationDuration, animations: {
            self.bgView.y = SCREENH
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    // MARK: - HomeTwoViewDelegate
    func clickshare(button: UIButton) {
        if let shareButtonType = WShareButtonType(rawValue: button.tag) {
            switch shareButtonType {
            case .WeChatSession:
                share(sdkType: SSDKPlatformType.subTypeWechatTimeline)
                break
            case .WeChatTimeline:
                share(sdkType: SSDKPlatformType.typeWechat)
                break
            case .Weibo:
                share(sdkType: SSDKPlatformType.typeSinaWeibo)
                break
            case .QZone:
                share(sdkType: SSDKPlatformType.subTypeQQFriend)
                break
            case .QQFriends:
                share(sdkType: SSDKPlatformType.typeQQ)
                break
            case .CopyLink:
                let url = BASE_URL + "ofdi/searchdetail/\((mpro?.catid)!)/\((mpro?.id)!)/\((mpro?.project_sn)!)"
                UIPasteboard.general.string = url
                SVProgressHUD.showInfo(withStatus: "项目链接已复制到粘贴板！")
                break
            }
        }
    }
    
    
    func share(sdkType: SSDKPlatformType){
        // 1.创建分享参数
        let mimage = UIImageView()
        if (mpro?.thumb!.isEmpty)!{
            mimage.image = UIImage(named:"default_bg")
        }else{
            mimage.kf.setImage(with: URL(string: (mpro?.thumb!)!)!, placeholder: UIImage(named: "default_bg"), options: nil, progressBlock: nil)
        }
        let url: String = BASE_URL + "ofdi/searchdetailm/\((mpro?.catid)!)/\((mpro?.id)!)/\((mpro?.project_sn)!)"
        
        let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        
        print("------")
        print("\(url)")
        print("\(URL(string: encodedString!))")
        print("\(NSURL(string: encodedString!))")
        print("\(mimage.image!)")
        print("\((mpro?.description_)!)")
        print("------")
        let shareParames = NSMutableDictionary()
        shareParames.ssdkSetupShareParams(byText: (mpro?.description_)!,
                                          images : mimage.image!,
                                          url : URL(string: encodedString!)!,
                                          title : (mpro?.title)!,
                                          type : SSDKContentType.webPage)
        
        //2.进行分享 SSDKPlatformType.typeSinaWeibo
        ShareSDK.share(sdkType, parameters: shareParames) { (state : SSDKResponseState, nil, entity : SSDKContentEntity?, error :Error?) in
            
            switch state{
                
            case SSDKResponseState.success: print("分享成功")
            case SSDKResponseState.fail:
                print("授权失败,错误描述:\(error)")
                SVProgressHUD.showInfo(withStatus: "分享失败，请检查设备是否安装此软件或网络连接情况")
            case SSDKResponseState.cancel:
                print("操作取消")
                SVProgressHUD.showInfo(withStatus: "分享取消")
                
            default:
                break
            }
            
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
